package com.easycode.devtool.util;

import java.io.UnsupportedEncodingException;

/**
 * 编码相关操作类
 */
public final class EncodingUtils
{
    //java.net.URLEncoder.encode()

    /*
    功能：UrlEncode编码
     */
    public static String urlEncode(String str)
    {
        return urlEncode(str,"utf-8");
    }
    public static String urlEncode(String str,String encoding)
    {
        if(StringUtils.isEmpty(str)) return "";

        String s = "";
        try {
            s  =  java.net.URLEncoder.encode(str, encoding);
        }
        catch (UnsupportedEncodingException e){;}
        finally
        {
            return s;
        }
    }

    /*
    功能：UrlDecode解码
     */
    public static String urlDecode(String str)
    {
        return urlDecode(str, "utf-8");
    }
    public static String urlDecode(String str,String encoding)
    {
        if(StringUtils.isEmpty(str)) return "";

        String s = "";
        try {
            s  =  java.net.URLDecoder.decode(str,encoding);
        }
        catch (UnsupportedEncodingException e){;}
        finally
        {
            return s;
        }
    }


    /*
   功能：htmlEncode编码

   (目前这个方法，临时写的，没有任何性能方面的考虑，真用的话，在进行测试吧)
    */
    public static String htmlEncode(String str)
    {
        if(StringUtils.isEmpty(str)) return "";

        str = str.replace("&", "&amp;");
        str = str.replace("<", "&lt;");
        str = str.replace(">", "&gt;");
        str = str.replace("\r\n", "<br>");
        str = str.replace("\'", "&#39;");
        str = str.replace("\"", "&quot;");
        str = str.replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;");
        str = str.replace(" ", "&nbsp;");
        return (str);
    }


    /*
  功能：htmlDecode解码

  (目前这个方法，临时写的，没有任何性能方面的考虑，真用的话，在进行测试吧)
   */
    public static String htmlDecode(String str)
    {
        if(StringUtils.isEmpty(str)) return "";

        str = str.replace("&amp;", "&");
        str = str.replace("&lt;", "<");
        str = str.replace("&gt;", ">");
        str = str.replace("<br>", "\r\n");
        str = str.replace("&#39;", "\'");
        str = str.replace("&quot;", "\"");
        str = str.replace("&nbsp;", " ");
        str = str.replace("&nbsp;&nbsp;&nbsp;&nbsp;", "\t");
        return (str);
    }

}
